import pandas as pd

# 用户数据
user_data = {
    'user_id': [1, 2, 3],
    'age': [25, 32, 45],
    'gender': ['M', 'F', 'M'],
    'location': ['北京', '上海', '广州'],
    'member_level': ['gold', 'silver', 'bronze']
}

# 商品数据
item_data = {
    'item_id': [101, 102, 103],
    'category': ['电子产品', '服装', '家居'],
    'price': [2999, 299, 599],
    'brand': ['Apple', 'Nike', 'IKEA'],
    'tags': ['新品', '热卖', '折扣']
}

# 交互数据
interaction_data = {
    'user_id': [1, 1, 2, 2, 3],
    'item_id': [101, 102, 101, 103, 102],
    'behavior': ['click', 'purchase', 'view', 'cart', 'click'],
    'timestamp': ['2023-10-01', '2023-10-02', '2023-10-03', '2023-10-04', '2023-10-05']
}
# 提取特征
def create_features(user_data, item_data, interaction_data):
    """创建推荐系统特征"""
    # 用户特征
    user_features = user_data.copy()
    user_features['age_group'] = pd.cut(user_features['age'], bins=[0, 18, 25, 35, 50, 100], labels=['<18', '18-25', '26-35', '36-50', '>50'])

    # 商品特征
    item_features = item_data.copy()
    item_features['price_level'] = pd.cut(item_features['price'], bins=[0, 100, 500, 1000, 5000, 10000], labels=['低', '中低', '中', '中高', '高'])

    # 交互特征
    interaction_features = interaction_data.copy()
    interaction_features['behavior_weight'] = interaction_features['behavior'].map({
        'view': 0.2,
        'click': 0.5,
        'cart': 0.8,
        'purchase': 1.0
    })

    # 时间特征
    interaction_features['timestamp'] = pd.to_datetime(interaction_features['timestamp'])
    interaction_features['hour'] = interaction_features['timestamp'].dt.hour
    interaction_features['day_of_week'] = interaction_features['timestamp'].dt.dayofweek

    # 合并特征
    merged_features = pd.merge(
        interaction_features,
        user_features,
        on='user_id'
    )
    merged_features = pd.merge(
        merged_features,
        item_features,
        on='item_id'
    )

    return merged_features

create_features(user_data,item_data,interaction_data)

